<template>
    <div class="common-layout">
        <el-container>
            <el-header style="border-style: groove;border-width: 0px;margin-bottom: 12px;">
                <el-card style="height: 120px;">
                    <el-form :inline="true">
                        <el-form-item label="客户" style="width: 220px;">
                            <el-input v-model="info.customercode" placeholder="请输入客户名称/编号" />
                        </el-form-item>
                        <el-form-item label="状态" style="width: 210px;">
                            <el-select clearable v-model="info.customerState">
                                <el-option label="启用" :value="0" />
                                <el-option label="禁用" :value="1" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="所属行业" style="width: 220px;">
                            <el-select clearable v-model="info.industryId">
                                <el-option v-for="item in Industry" :label="item.industryName"
                                    :value="item.industryId" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="联系人" style="width: 220px;">
                            <el-select clearable v-model="info.userid">
                                <el-option v-for="item in User" :label="item.userName" :value="item.userId" />
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-button @click="Reset()">重置</el-button>
                            <el-button type="primary" @click="GetCustomer">查询</el-button>
                            <el-button @click="drawerVisible = true">高级搜索</el-button>
                        </el-form-item>


                        <el-form-item>
                            <el-button type="success" @click="router.push('/CreateCustomer')">新增</el-button>
                            <el-button type="danger" @click="detail">批量删除</el-button>
                            <el-button type="warning" @click="ExportCustomer">导出</el-button>
                            <el-button @click="">导入</el-button>
                            <el-button type="primary" @click="refreshPage">刷新</el-button>
                            <el-button @click="showColumnSettings = true">表头设置</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>
            </el-header>
            <el-main style="border-style: groove;border-width: 0px;margin-top: 7px;">
                <el-card style="margin-top: 30px;">
                    <el-table ref="multipleTableRef" :data="tableData" row-key="customerId" style="width: 100%"
                        @selection-change="handleSelectionChange" stripe border>
                        <el-table-column type="selection" :selectable="selectable" width="55" fixed="left" />
                        <el-table-column type="index" label="#" width="50" fixed="left" />                    
                        <!-- 动态生成列 -->
                        <template v-for="column in visibleColumns" :key="column.key">
                            <!-- 客户编码列 -->
                            <el-table-column v-if="column.key === 'customerCode'" prop="customerCode"
                                :label="column.label" width="140" fixed="left" show-overflow-tooltip>
                                <template v-slot="scope">
                                    <el-link type="success" @click="goCustomerDetail(scope.row)">
                                        {{ scope.row.customerCode }}
                                    </el-link>
                                </template>
                            </el-table-column>

                            <!-- 客户名称列 -->
                            <el-table-column v-else-if="column.key === 'customerName'" prop="customerName"
                                :label="column.label" :width="getColumnWidth(column.key)" 
                                :fixed="column.fixed ? 'left' : false" show-overflow-tooltip />

                            <!-- 所属行业列 -->
                            <el-table-column v-else-if="column.key === 'industryName'"
                                :label="column.label" :width="getColumnWidth(column.key)" 
                                :fixed="column.fixed ? 'left' : false" show-overflow-tooltip>
                                <template v-slot="scope">
                                    {{ scope.row.industryName || industryNameMap[scope.row.industryId] || '--' }}
                                </template>
                            </el-table-column>

                            <!-- 客户来源列 -->
                            <el-table-column v-else-if="column.key === 'customerSourceName'"
                                :label="column.label" :width="getColumnWidth(column.key)" 
                                :fixed="column.fixed ? 'left' : false" show-overflow-tooltip>
                                <template v-slot="scope">
                                    {{ scope.row.customerSourceName || customerSourceNameMap[scope.row.customerSourceId] || '--' }}
                                </template>
                            </el-table-column>

                            <!-- 名称列（账户名称） -->
                            <el-table-column v-else-if="column.key === 'financeName'" prop="financeName"
                                :label="column.label" :width="getColumnWidth(column.key)" show-overflow-tooltip />

                            <!-- 纳税人识别号列 -->
                            <el-table-column v-else-if="column.key === 'taxpayerNumber'" prop="taxpayerNumber"
                                :label="column.label" :width="getColumnWidth(column.key)" show-overflow-tooltip>
                                <template v-slot="scope">
                                    <span class="number-text">{{ scope.row.taxpayerNumber || '--' }}</span>
                                </template>
                            </el-table-column>

                            <!-- 银行账户列 -->
                            <el-table-column v-else-if="column.key === 'bankAccount'" prop="bankAccount"
                                :label="column.label" :width="getColumnWidth(column.key)" show-overflow-tooltip>
                                <template v-slot="scope">
                                    <span class="number-text">{{ scope.row.bankAccount || '--' }}</span>
                                </template>
                            </el-table-column>

                            <!-- 开户银行列 -->
                            <el-table-column v-else-if="column.key === 'accountBank'" prop="accountBank"
                                :label="column.label" :width="getColumnWidth(column.key)" show-overflow-tooltip />

                            <!-- 开户行地址列 -->
                            <el-table-column v-else-if="column.key === 'bankAddress'" prop="bankAddress"
                                :label="column.label" :width="getColumnWidth(column.key)" show-overflow-tooltip />

                            <!-- 客户地址列 -->
                            <el-table-column v-else-if="column.key === 'contactAddress'" prop="contactAddress"
                                :label="column.label" :width="getColumnWidth(column.key)" show-overflow-tooltip />

                            <!-- 状态列 -->
                            <el-table-column v-else-if="column.key === 'customerState'" prop="customerState"
                                :label="column.label" width="100" :fixed="column.fixed ? 'left' : false">
                                <template v-slot="scope">
                                    <el-tag type="success" v-if="scope.row.customerState == 0" size="small">启用</el-tag>
                                    <el-tag type="danger" v-if="scope.row.customerState == 1" size="small">禁用</el-tag>
                                </template>
                            </el-table-column>

                            <!-- 操作人列 -->
                            <el-table-column v-else-if="column.key === 'createor'" prop="createor"
                                :label="column.label" width="100" :fixed="column.fixed ? 'left' : false">
                                <template v-slot="scope">
                                    {{ scope.row.createor || currentUserName }}
                                </template>
                            </el-table-column>

                            <!-- 操作时间列 -->
                            <el-table-column v-else-if="column.key === 'createrTime'" prop="createrTime"
                                :label="column.label" width="120" :fixed="column.fixed ? 'left' : false">
                                <template v-slot="scope">
                                    {{ scope.row.createrTime ? moment(scope.row.createrTime).format('YYYY-MM-DD') : currentTime }}
                                </template>
                            </el-table-column>

                            <!-- 普通列 -->
                            <el-table-column v-else :prop="column.key" :label="column.label"
                                :width="getColumnWidth(column.key)" :fixed="column.fixed ? 'left' : false" 
                                show-overflow-tooltip />
                        </template>

                        <el-table-column fixed="right" label="操作" width="140" align="center">
                            <template #default="scope">
                                <el-button link type="primary" size="small" @click="goEdit(scope.row)">编辑</el-button>
                                <el-button link type="danger" size="small"
                                    @click="SupplierDelete(scope.row.customerId)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                </el-card>

            </el-main>

        </el-container>

    </div>
    <el-card style="margin-top: 15px;">
        <div class="pager-bar">
            <div class="pager-group">
                <el-button size="small" @click="goFirstPage" :disabled="page.pageindex <= 1">首页</el-button>
                <el-button size="small" @click="goPrevPage" :disabled="page.pageindex <= 1">上一页</el-button>
                <el-button size="small" @click="goNextPage" :disabled="page.pageindex >= page.pageCount">下一页</el-button>
                <el-button size="small" @click="goLastPage" :disabled="page.pageindex >= page.pageCount">尾页</el-button>
            </div>
            <el-pagination size="small" v-model:current-page="page.pageindex" v-model:page-size="page.pagesize"
                :page-sizes="[5, 10, 20, 30]" :background="true" layout="sizes, prev, pager, next, jumper"
                :total="page.listCount" />
            <div class="pager-info">共 {{ page.listCount }} 条｜共 {{ page.pageCount }} 页｜当前第 {{ page.pageindex }} 页</div>
        </div>
    </el-card>

    <!-- 表头设置弹窗 -->
    <el-dialog v-model="showColumnSettings" title="表头设置" width="500px" :close-on-click-modal="false">
        <div class="column-settings">
            <div class="settings-header">
                <span>显示</span>
                <span>表头名称</span>
                <span>固定排序</span>
            </div>

            <div class="column-list">
                <div v-for="(column, index) in allColumns" :key="column.key" class="column-item">
                    <el-checkbox v-model="column.visible" />
                    <span class="column-name">{{ column.label }}</span>
                    <div class="column-actions">
                        <el-button size="small" text @click="moveColumn(index, -1)" :disabled="index === 0">
                            ↑
                        </el-button>
                        <el-button size="small" text @click="moveColumn(index, 1)"
                            :disabled="index === allColumns.length - 1">
                            ↓
                        </el-button>
                    </div>
                </div>
            </div>
        </div>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="resetColumnSettings">外观重置</el-button>
                <el-button @click="showColumnSettings = false">取消</el-button>
                <el-button type="primary" @click="saveColumnSettings">确定</el-button>
            </div>
        </template>
    </el-dialog>

    <el-drawer v-model="drawerVisible" direction="rtl" size="28%" class="advanced-search-drawer"
        :before-close="handleDrawerClose">
        <template #header>
            <div class="drawer-header">
                <el-icon class="header-icon">
                    <Search />
                </el-icon>
                <span class="header-title">高级搜索</span>
            </div>
        </template>

        <div class="drawer-content">
            <el-form :model="advancedSearch" label-width="110px" class="advanced-search-form">
                <!-- 基础信息区域 -->
                <div class="search-section">
                    <div class="section-header">
                        <el-icon class="section-icon">
                            <UserIcon />
                        </el-icon>
                        <span class="section-title">基础信息</span>
                    </div>
                    <el-row :gutter="12">
                        <el-col :span="24">
                            <el-form-item label="客户编码" label-width="80px">
                                <el-input v-model="advancedSearch.customerCode" placeholder="请输入客户编码" clearable
                                    prefix-icon="Document" size="small" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="12">
                        <el-col :span="24">
                            <el-form-item label="客户名称" label-width="80px">
                                <el-input v-model="advancedSearch.customerName" placeholder="请输入客户名称" clearable
                                    prefix-icon="UserIcon" size="small" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="12">
                        <el-col :span="24">
                            <el-form-item label="所属行业" label-width="80px">
                                <el-select v-model="advancedSearch.industryId" placeholder="请选择所属行业" clearable
                                    style="width: 100%" prefix-icon="OfficeBuilding" size="small">
                                    <el-option v-for="item in Industry" :key="item.industryId"
                                        :label="item.industryName" :value="item.industryId" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="12">
                        <el-col :span="24">
                            <el-form-item label="客户来源" label-width="80px">
                                <el-select v-model="advancedSearch.customerSourceId" placeholder="请选择客户来源" clearable
                                    style="width: 100%" prefix-icon="Link" size="small">
                                    <el-option v-for="item in CustomerSource" :key="item.customerSourceId"
                                        :label="item.customerSourceName" :value="item.customerSourceId" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="12">
                        <el-col :span="24">
                            <el-form-item label="客户状态" label-width="80px">
                                <el-select v-model="advancedSearch.customerState" placeholder="请选择客户状态" clearable
                                    style="width: 100%" size="small">
                                    <el-option label="启用" :value="0">
                                        <span style="color: #67c23a;">● 启用</span>
                                    </el-option>
                                    <el-option label="禁用" :value="1">
                                        <span style="color: #f56c6c;">● 禁用</span>
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="12">
                        <el-col :span="24">
                            <el-form-item label="操作时间" label-width="80px">
                                <el-date-picker v-model="advancedSearch.createTimeRange" type="daterange"
                                    start-placeholder="开始日期" end-placeholder="结束日期" format="YYYY-MM-DD"
                                    value-format="YYYY-MM-DD" style="width: 100%" prefix-icon="Calendar" size="small" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>

                <!-- 联系信息区域 -->
                <div class="search-section">
                    <div class="section-header">
                        <el-icon class="section-icon">
                            <Phone />
                        </el-icon>
                        <span class="section-title">联系信息</span>
                    </div>
                    <el-row :gutter="12">
                        <el-col :span="24">
                            <el-form-item label="联系人" label-width="80px">
                                <el-input v-model="advancedSearch.customerContact" placeholder="请输入联系人" clearable
                                    prefix-icon="Avatar" size="small" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="12">
                        <el-col :span="24">
                            <el-form-item label="联系电话" label-width="80px">
                                <el-input v-model="advancedSearch.contactPhone" placeholder="请输入联系电话" clearable
                                    prefix-icon="Phone" size="small" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="12">
                        <el-col :span="24">
                            <el-form-item label="电子邮箱" label-width="80px">
                                <el-input v-model="advancedSearch.customerEmail" placeholder="请输入电子邮箱" clearable
                                    prefix-icon="Message" size="small" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="12">
                        <el-col :span="24">
                            <el-form-item label="客户地址" label-width="80px">
                                <el-input v-model="advancedSearch.contactAddress" placeholder="请输入客户地址" clearable
                                    prefix-icon="Location" size="small" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>

                <!-- 销售信息区域 -->
                <div class="search-section">
                    <div class="section-header">
                        <el-icon class="section-icon">
                            <Briefcase />
                        </el-icon>
                        <span class="section-title">销售信息</span>
                    </div>
                    <el-row :gutter="12">
                        <el-col :span="24">
                            <el-form-item label="销售部门" label-width="80px">
                                <el-input v-model="advancedSearch.organizationName" placeholder="请选择销售部门" readonly
                                    @click="openAdvancedOrgDialog" class="select-input" size="small">
                                    <template #prefix>
                                        <el-icon>
                                            <OfficeBuilding />
                                        </el-icon>
                                    </template>
                                    <template #suffix>
                                        <el-icon class="search-icon">
                                            <Search />
                                        </el-icon>
                                    </template>
                                </el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="12">
                        <el-col :span="24">
                            <el-form-item label="销售负责人" label-width="90px">
                                <el-input v-model="advancedSearch.userName" placeholder="请选择销售负责人" readonly
                                    @click="openAdvancedUserDialog" class="select-input" size="small">
                                    <template #prefix>
                                        <el-icon>
                                            <Avatar />
                                        </el-icon>
                                    </template>
                                    <template #suffix>
                                        <el-icon class="search-icon">
                                            <Search />
                                        </el-icon>
                                    </template>
                                </el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="12">
                        <el-col :span="24">
                            <el-form-item label="操作人" label-width="80px">
                                <el-input v-model="advancedSearch.createor" placeholder="请输入操作人" clearable
                                    prefix-icon="UserIcon" size="small" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>

                <!-- 财务信息区域 -->
                <div class="search-section">
                    <div class="section-header">
                        <el-icon class="section-icon">
                            <CreditCard />
                        </el-icon>
                        <span class="section-title">财务信息</span>
                    </div>
                    <el-row :gutter="12">
                        <el-col :span="24">
                            <el-form-item label="账户名称" label-width="80px">
                                <el-input v-model="advancedSearch.financeName" placeholder="请输入账户名称" clearable
                                    prefix-icon="Wallet" size="small" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="12">
                        <el-col :span="24">
                            <el-form-item label="银行账户" label-width="80px">
                                <el-input v-model="advancedSearch.bankAccount" placeholder="请输入银行账户" clearable
                                    prefix-icon="CreditCard" size="small" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="12">
                        <el-col :span="24">
                            <el-form-item label="纳税人识别号" label-width="98px">
                                <el-input v-model="advancedSearch.taxpayerNumber" placeholder="请输入纳税人识别号" clearable
                                    prefix-icon="Document" size="small" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="12">
                        <el-col :span="24">
                            <el-form-item label="开户银行" label-width="80px">
                                <el-input v-model="advancedSearch.accountBank" placeholder="请输入开户银行" clearable
                                    prefix-icon="OfficeBuilding" size="small" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>
            </el-form>
        </div>

        <template #footer>
            <div class="drawer-footer">
                <div class="footer-actions">
                    <el-button size="small" @click="resetAdvancedSearch">重置</el-button>
                    <el-button size="small" @click="drawerVisible = false">取消</el-button>
                    <el-button size="small" type="primary" @click="searchWithAdvanced">查询</el-button>
                </div>
            </div>
        </template>
    </el-drawer>

    <!-- 高级搜索部门选择对话框 -->
    <el-dialog v-model="showAdvancedOrgDialog" title="选择部门" width="600px">
        <div style="margin-bottom: 16px;">
            <el-input v-model="advancedOrgSearchText" placeholder="搜索部门名称" clearable>
                <template #prefix>
                    <el-icon>
                        <Search />
                    </el-icon>
                </template>
            </el-input>
        </div>
        <el-table :data="filteredAdvancedOrgList" @row-click="handleSelectAdvancedOrg" style="cursor: pointer;">
            <el-table-column prop="organizationName" label="部门名称" />
            <el-table-column prop="organizationCode" label="部门编码" />
        </el-table>
    </el-dialog>

    <!-- 高级搜索用户选择对话框 -->
    <el-dialog v-model="showAdvancedUserDialog" title="选择用户" width="400px">
        <div style="margin-bottom: 16px;">
            <el-input v-model="advancedUserSearchText" placeholder="搜索用户名称" clearable>
                <template #prefix>
                    <el-icon>
                        <Search />
                    </el-icon>
                </template>
            </el-input>
        </div>
        <el-table :data="filteredAdvancedUserList" @row-click="handleSelectAdvancedUser" style="cursor: pointer;">
            <el-table-column prop="userName" label="用户名称" />
        </el-table>
    </el-dialog>
</template>
<script lang="ts" setup>
import myaxios from '@/http/MyAxios';
import router from '@/router';
import axios from 'axios';
import { ElMessage, ElMessageBox, SCOPE } from 'element-plus';
import {
    Search, User as UserIcon, Phone, Briefcase, CreditCard,
    Document, OfficeBuilding, Avatar, Message,
    Location, Wallet, Calendar, Link, RefreshLeft,
    Close
} from '@element-plus/icons-vue';
import moment from 'moment';
import { reactive, ref, onMounted, watch, computed } from 'vue';
// 获取当前登录用户和当前时间
const currentUserName = ref('')
const currentTime = computed(() => {
    return moment().format('YYYY-MM-DD')
})

// 从后端获取当前登录用户的真实姓名
const loadCurrentUser = async () => {
    try {
        const res = await myaxios.get('/api/User/GetMyProfile')
        const droot: any = res?.data ?? {}
        const d: any = (droot?.data && Object.keys(droot).length <= 3) ? (droot.data || {}) : droot
        if (d) {
            // 优先使用真实姓名，其次用户名，最后账号
            currentUserName.value = d.userName || d.realName || d.nickname || localStorage.getItem('username') || ''
            // 如果获取到了，更新localStorage
            if (currentUserName.value) {
                localStorage.setItem('username', currentUserName.value)
            }
        } else {
            // 如果接口失败，使用localStorage中的值
            currentUserName.value = localStorage.getItem('username') || ''
        }
    } catch (error) {
        // 如果接口失败，使用localStorage中的值
        console.warn('获取当前用户信息失败，使用本地存储的值:', error)
        currentUserName.value = localStorage.getItem('username') || ''
    }
}

//客户参数
const info = reactive({
    customercode: '',//客户编码
    customerState: '',//客户状态
    industryId: '',//行业
    userid: '',//进货负责人
})

// 表头设置相关
const showColumnSettings = ref(false)

// 定义列类型
interface ColumnConfig {
    key: string
    label: string
    visible: boolean
    fixed: boolean
}

// 定义所有可用的列
const allColumns = ref<ColumnConfig[]>([
    { key: 'customerCode', label: '客户编码', visible: true, fixed: true },
    { key: 'customerName', label: '客户名称', visible: true, fixed: true },
    { key: 'industryName', label: '所属行业', visible: true, fixed: false },
    { key: 'customerSourceName', label: '客户来源', visible: true, fixed: false },
    { key: 'customerContact', label: '联系人', visible: true, fixed: false },
    { key: 'contactPhone', label: '联系电话', visible: true, fixed: false },
    { key: 'customerEmail', label: '电子邮箱', visible: true, fixed: false },
    { key: 'organizationName', label: '销售部门', visible: true, fixed: false },
    { key: 'userName', label: '销售负责人', visible: true, fixed: false },
    { key: 'customerState', label: '状态', visible: true, fixed: false },
    { key: 'contactAddress', label: '客户地址', visible: true, fixed: false },
    { key: 'financeName', label: '账户名称', visible: true, fixed: false },
    { key: 'taxpayerNumber', label: '纳税人识别号', visible: true, fixed: false },
    { key: 'bankAccount', label: '银行账户', visible: true, fixed: false },
    { key: 'accountBank', label: '开户银行', visible: true, fixed: false },
    { key: 'bankAddress', label: '开户行地址', visible: true, fixed: false },
    { key: 'createor', label: '操作人', visible: true, fixed: false },
    { key: 'createrTime', label: '操作时间', visible: true, fixed: false }
])

// 计算显示的列
const visibleColumns = computed<ColumnConfig[]>(() => {
    return allColumns.value.filter(col => col.visible)
})

// 保存列设置
const saveColumnSettings = () => {
    // 这里可以将设置保存到localStorage或发送到后端
    localStorage.setItem('customerTableColumns', JSON.stringify(allColumns.value))
    showColumnSettings.value = false
    ElMessage.success('表头设置已保存')
}

// 重置列设置
const resetColumnSettings = () => {
    allColumns.value.forEach(col => {
        col.visible = true
        col.fixed = ['customerCode', 'customerName'].includes(col.key)
    })
}

// 获取列宽度
const getColumnWidth = (key: string) => {
    const widthMap: Record<string, number> = {
        customerName: 160,
        industryName: 120,
        customerSourceName: 120,
        customerContact: 100,
        contactPhone: 130,
        customerEmail: 180,
        organizationName: 120,
        userName: 120,
        contactAddress: 200,
        financeName: 150,
        taxpayerNumber: 160,
        bankAccount: 180,
        accountBank: 150,
        bankAddress: 200,
        createor: 100
    }
    return widthMap[key] || 120
}

// 移动列位置
const moveColumn = (index: number, direction: number) => {
    const newIndex = index + direction
    if (newIndex >= 0 && newIndex < allColumns.value.length) {
        const columns: ColumnConfig[] = [...allColumns.value]
        const temp = columns[index]
        if (temp && columns[newIndex]) {
            columns[index] = columns[newIndex]
            columns[newIndex] = temp
            allColumns.value = columns
        }
    }
}

// 加载列设置
const loadColumnSettings = () => {
    const saved = localStorage.getItem('customerTableColumns')
    if (saved) {
        try {
            const savedColumns: ColumnConfig[] = JSON.parse(saved)
            if (Array.isArray(savedColumns) && savedColumns.length === allColumns.value.length) {
                // 验证每个保存的列配置是否有效
                const isValid = savedColumns.every(col =>
                    col &&
                    typeof col.key === 'string' &&
                    typeof col.label === 'string' &&
                    typeof col.visible === 'boolean' &&
                    typeof col.fixed === 'boolean'
                )
                if (isValid) {
                    allColumns.value = savedColumns
                }
            }
        } catch (error) {
            console.warn('Failed to load column settings:', error)
        }
    }
}
//分页
const page = reactive({
    pageindex: 1,//页码
    pagesize: 10,//每页条数
    listCount: 0,//总条数
    pageCount: 0,//总页数
})
//抽屉显示状态
const drawerVisible = ref(false)

// 高级搜索参数
const advancedSearch = reactive({
    customerCode: '',
    customerName: '',
    industryId: '',
    customerSourceId: '',
    customerContact: '',
    contactPhone: '',
    customerEmail: '',
    organizationId: '',
    organizationName: '',
    userId: '',
    userName: '',
    customerState: '',
    contactAddress: '',
    financeName: '',
    taxpayerNumber: '',
    bankAccount: '',
    accountBank: '',
    createor: '',
    createTimeRange: []
})

// 高级搜索对话框状态
const showAdvancedOrgDialog = ref(false)
const showAdvancedUserDialog = ref(false)
const advancedOrgSearchText = ref('')
const advancedUserSearchText = ref('')

// 高级搜索部门用户列表
const advancedOrgList = ref([])
const advancedUserList = ref([])
//重置
const Reset = () => {
    info.industryId = ''
    info.customerState = ''
    info.userid = ''
    info.customercode = ''
}

// 客户数据源
const tableData = ref<any[]>([])
const enrichCustomerRow = (row: any) => {
    if (!row) return row
    const industryKey = row.industryId !== undefined && row.industryId !== null ? String(row.industryId) : ''
    const sourceKey = row.customerSourceId !== undefined && row.customerSourceId !== null ? String(row.customerSourceId) : ''
    return {
        ...row,
        industryName: row.industryName || (industryKey ? industryNameMap.value[industryKey] || '' : ''),
        customerSourceName: row.customerSourceName || (sourceKey ? customerSourceNameMap.value[sourceKey] || '' : '')
    }
}
const GetCustomer = () => {
    myaxios.get('/api/Customer/GetCustomer', {
        params: {
            customercode: info.customercode, //供应商名称/编号
            customerState: info.customerState, //状态
            industryId: info.industryId, //行业
            userId: info.userid, //进货负责人
            pageindex: page.pageindex, //页码
            pagesize: page.pagesize //每页条数   
        }
    }).then(res => {
        const list = res.data?.data?.data || []
        tableData.value = list.map((item: any) => enrichCustomerRow(item));
        page.listCount = res.data.data.listCount;
        page.pageCount = res.data.data.pageCount;
    })
}

// 刷新当前页面
const refreshPage = () => {
    window.location.reload()
}

//行业下拉框
const Industry: any = ref([]);
const GetIndustry = () => {
    myaxios.get('api/Supplier/GetIndustry').then(res => {
        if (res.data?.data && Array.isArray(res.data.data) && res.data.data.length > 0) {
            Industry.value = res.data.data;
        }
    })
}

const industryNameMap = computed<Record<string, string>>(() => {
    const map: Record<string, string> = {}
    const list = Array.isArray(Industry.value) ? Industry.value : []
    list.forEach((item: any) => {
        const id = item?.industryId ?? item?.dictionaryId
        if (id !== undefined && id !== null) {
            map[String(id)] = item?.industryName ?? item?.dictionaryName ?? ''
        }
    })
    return map
})
//用户下拉框
const User: any = ref([]);
const GetUser = () => {
    myaxios.get('api/Supplier/GetUser').then(res => {
        User.value = res.data.data;

    })
}
//客户来源下拉框
const CustomerSource: any = ref([]);
const GetCustomerSource = () => {
    myaxios.get('api/Customer/GetCustomerSource').then(res => {
        if (res.data?.data && Array.isArray(res.data.data) && res.data.data.length > 0) {
            CustomerSource.value = res.data.data;
        }
    })
}

const customerSourceNameMap = computed<Record<string, string>>(() => {
    const map: Record<string, string> = {}
    const list = Array.isArray(CustomerSource.value) ? CustomerSource.value : []
    list.forEach((item: any) => {
        const id = item?.customerSourceId ?? item?.dictionaryId
        if (id !== undefined && id !== null) {
            map[String(id)] = item?.customerSourceName ?? item?.dictionaryName ?? ''
        }
    })
    return map
})

const isRootDictionary = (item: any) =>
    !item?.parentId || item.parentId === 0 || item.parentId === '0' || item.parentId === null

const matchDictionary = (item: any, names: string[], codes: string[]) => {
    const name = (item?.dictionaryName || '').toLowerCase()
    const code = (item?.dictionaryCode || '').toLowerCase()
    return names.some(n => name === n.toLowerCase() || name.includes(n.toLowerCase())) ||
        codes.some(c => code === c.toLowerCase())
}

const findDictionaryParentId = async (nameCandidates: string[], codeCandidates: string[]) => {
    const params = { Pageindex: 1, PageSize: 1000 }
    try {
        const res = await myaxios.get('/api/Dictionary/GetDictionaryList', { params })
        const list = res.data?.data?.data || []
        const found = list.find((item: any) => isRootDictionary(item) && matchDictionary(item, nameCandidates, codeCandidates))
        if (found?.dictionaryId) return found.dictionaryId
    } catch (error) {
        console.warn('获取字典列表失败', error)
    }

    for (const name of nameCandidates) {
        try {
            const res = await myaxios.get('/api/Dictionary/GetDictionaryList', {
                params: { DictionaryName: name, Pageindex: 1, PageSize: 200 }
            })
            const list = res.data?.data?.data || []
            const found = list.find((item: any) => isRootDictionary(item))
            if (found?.dictionaryId) return found.dictionaryId
        } catch (error) {
            console.warn(`按名称 ${name} 获取字典失败`, error)
        }
    }
    return null
}

const fetchDictionaryChildren = async (parentId: string | number | null) => {
    if (!parentId) return []
    try {
        const res = await myaxios.get('/api/Dictionary/GetDictionaryChildren', {
            params: { ParentId: parentId, Pageindex: 1, PageSize: 1000 }
        })
        return res.data?.data?.data || []
    } catch (error) {
        console.warn('获取字典子项失败', error)
        return []
    }
}

const loadIndustryList = async () => {
    const parentId = await findDictionaryParentId(['所属行业', '行业'], ['industry'])
    const children = await fetchDictionaryChildren(parentId)
    if (children.length > 0) {
        Industry.value = children.map((item: any) => ({
            industryId: item.dictionaryId,
            industryName: item.dictionaryName
        }))
    }
}

const loadCustomerSourceList = async () => {
    const parentId = await findDictionaryParentId(['客户来源'], ['customersource', 'customer_source'])
    const children = await fetchDictionaryChildren(parentId)
    if (children.length > 0) {
        CustomerSource.value = children.map((item: any) => ({
            customerSourceId: item.dictionaryId,
            customerSourceName: item.dictionaryName
        }))
    }
}
watch(page, () => {
    GetCustomer();
})

watch([Industry, CustomerSource], () => {
    tableData.value = tableData.value.map((item: any) => enrichCustomerRow(item))
})

onMounted(() => {
    GetCustomer(); //获取客户数据
    GetIndustry(); //获取行业数据
    loadIndustryList(); //行业字典
    GetUser(); //获取用户数据
    loadColumnSettings(); //加载列设置
    GetCustomerSource(); //获取客户来源数据
    loadCustomerSourceList(); //客户来源字典
    loadCurrentUser(); //获取当前登录用户信息
})

//删除
const SupplierDelete = (customerid: any) => {
    ElMessageBox.confirm(
        '确认删除该条数据吗?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {

            axios.put('http://localhost:8080/api/Customer/DeleteCustomer?customerid=' + customerid).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success(res.data.message);
                    GetCustomer(); //获取客户数据

                }
                else {
                    ElMessage.error(res.data.message);
                }
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '客户删除已取消!',
            })
        })
}
//批量删除
const handleSelectionChange = (val: any) => {
    multipleSelection.value = val
}
const multipleTableRef = ref()
const multipleSelection = ref([])
const selectable = (row: any) => ![1, 2].includes(row.id)
const detail = (customerid: any) => {
    if (multipleSelection.value.length == 0) {
        ElMessage.error('请选择要删除的客户')
        return;
    }
    ElMessageBox.confirm(
        '确认删除该条数据吗?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )

        .then(() => {
            axios.put('http://localhost:8080/api/Customer/DeleteAllCustomer?customerids=' + multipleSelection.value.map((item: any) => item.customerId)).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success(res.data.message);
                    GetCustomer();//获取客户数据
                }
                else {
                    ElMessage.error(res.data.message);
                }
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '批量删除客户已取消!',
            })
        })
}
//详情
const goCustomerDetail = (row: any) => {
    router.push({
        path: '/DetailCustomer',
        query: {
            customerId: row.customerId
        }
    })
}
const goFirstPage = () => {
    if (page.pageindex > 1) {
        page.pageindex = 1
    }
}

const goPrevPage = () => {
    if (page.pageindex > 1) {
        page.pageindex -= 1
    }
}

const goNextPage = () => {
    if (page.pageindex < page.pageCount) {
        page.pageindex += 1
    }
}

const goLastPage = () => {
    if (page.pageCount > 0 && page.pageindex < page.pageCount) {
        page.pageindex = page.pageCount
    }
}

// 跳转编辑
const goEdit = (row: any) => {
    // 缓存客户数据到 sessionStorage，实现立即显示
    const CUSTOMER_EDIT_CACHE_KEY = 'customer_edit_cache'
    sessionStorage.setItem(CUSTOMER_EDIT_CACHE_KEY, JSON.stringify(row))
    
    router.push({
        path: '/UpdateWarehouse',
        query: { customerId: row.customerId }
    })
}

// 导出客户（按当前筛选与分页）
const ExportCustomer = () => {
    if (multipleSelection.value && multipleSelection.value.length > 0) {
        const headers = [
            '客户编码', '客户名称', '所属行业', '客户来源', '联系人', '联系电话', '电子邮箱', '销售部门', '销售负责人', '状态', '客户地址', '账户名称', '纳税人识别号', '银行账户', '开户银行', '开户行地址', '操作人', '操作时间'
        ];
        const rows = multipleSelection.value.map((x: any) => [
            x.customerCode ?? '',
            x.customerName ?? '',
            x.industryName ?? '',
            x.customerSourceName ?? '',
            x.customerContact ?? '',
            x.contactPhone ?? '',
            x.customerEmail ?? '',
            x.organizationName ?? '',
            x.userName ?? '',
            (x.customerState === 0 ? '启用' : '禁用'),
            x.contactAddress ?? '',
            x.financeName ?? '',
            x.taxpayerNumber ?? '',
            x.bankAccount ?? '',
            x.accountBank ?? '',
            x.bankAddress ?? '',
            (x.createor ?? ''),
            (x.createrTime ? moment(x.createrTime).format('YYYY-MM-DD HH:mm:ss') : '')
        ]);
        const escape = (v: any) => {
            const s = String(v).replace(/"/g, '""');
            return /[",\n]/.test(s) ? `"${s}"` : s;
        };
        const csv = [headers.map(escape).join(','), ...rows.map(r => r.map(escape).join(','))].join('\n');
        const blob = new Blob(['\ufeff' + csv], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        const url = URL.createObjectURL(blob);
        link.href = url;
        link.download = `客户_已选_${moment().format('YYYYMMDDHHmmss')}.csv`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(url);
        ElMessage.success('已导出所选数据');
        return;
    }
    axios.get('http://localhost:8080/api/Customer/ExportCustomerExcel', {
        params: {
            customercode: info.customercode,
            customerState: info.customerState,
            industryId: info.industryId,
            userid: info.userid,
            pageindex: page.pageindex,
            pagesize: page.pagesize
        },
        responseType: 'blob'
    }).then((res: any) => {
        const disposition = res.headers?.['content-disposition'] || res.headers?.['Content-Disposition'];
        let fileName = `客户_${moment().format('YYYYMMDDHHmmss')}.xlsx`;
        if (disposition) {
            const match = /filename\*=UTF-8''([^;]+)|filename="?([^";]+)"?/i.exec(disposition);
            if (match) {
                const raw = (match[1] ?? match[2]);
                if (typeof raw === 'string' && raw.length > 0) {
                    fileName = decodeURIComponent(raw);
                }
            }
        }

        const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        const link = document.createElement('a');
        const url = URL.createObjectURL(blob);
        link.href = url;
        link.download = fileName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(url);
        ElMessage.success('导出成功');
    }).catch((err: any) => {
        console.error(err);
        ElMessage.error('导出失败');
    })
}

// 高级搜索相关方法
// 获取高级搜索部门列表
const getAdvancedOrgList = () => {
    myaxios.get('api/Supplier/GetOrganization').then(res => {
        advancedOrgList.value = res.data.data || []
    }).catch(err => {
        console.error('获取部门列表失败:', err)
    })
}

// 获取高级搜索用户列表
const getAdvancedUserList = () => {
    myaxios.get('api/Supplier/GetUser').then(res => {
        advancedUserList.value = res.data.data || []
    }).catch(err => {
        console.error('获取用户列表失败:', err)
    })
}

// 过滤高级搜索部门列表
const filteredAdvancedOrgList = computed(() => {
    if (!advancedOrgSearchText.value) {
        return advancedOrgList.value
    }
    return advancedOrgList.value.filter((org: any) =>
        org.organizationName.toLowerCase().includes(advancedOrgSearchText.value.toLowerCase())
    )
})

// 过滤高级搜索用户列表
const filteredAdvancedUserList = computed(() => {
    if (!advancedUserSearchText.value) {
        return advancedUserList.value
    }
    return advancedUserList.value.filter((user: any) =>
        user.userName.toLowerCase().includes(advancedUserSearchText.value.toLowerCase())
    )
})

// 打开高级搜索部门对话框
const openAdvancedOrgDialog = () => {
    advancedOrgSearchText.value = ''
    getAdvancedOrgList()
    showAdvancedOrgDialog.value = true
}

// 打开高级搜索用户对话框
const openAdvancedUserDialog = () => {
    advancedUserSearchText.value = ''
    getAdvancedUserList()
    showAdvancedUserDialog.value = true
}

// 选择高级搜索部门
const handleSelectAdvancedOrg = (row: any) => {
    advancedSearch.organizationId = String(row.organizationId)
    advancedSearch.organizationName = row.organizationName
    showAdvancedOrgDialog.value = false
}

// 选择高级搜索用户
const handleSelectAdvancedUser = (row: any) => {
    advancedSearch.userId = String(row.userId)
    advancedSearch.userName = row.userName
    showAdvancedUserDialog.value = false
}

// 重置高级搜索
const resetAdvancedSearch = () => {
    advancedSearch.customerCode = ''
    advancedSearch.customerName = ''
    advancedSearch.industryId = ''
    advancedSearch.customerSourceId = ''
    advancedSearch.customerContact = ''
    advancedSearch.contactPhone = ''
    advancedSearch.customerEmail = ''
    advancedSearch.organizationId = ''
    advancedSearch.organizationName = ''
    advancedSearch.userId = ''
    advancedSearch.userName = ''
    advancedSearch.customerState = ''
    advancedSearch.contactAddress = ''
    advancedSearch.financeName = ''
    advancedSearch.taxpayerNumber = ''
    advancedSearch.bankAccount = ''
    advancedSearch.accountBank = ''
    advancedSearch.createor = ''
    advancedSearch.createTimeRange = []
}

// 抽屉关闭前的回调
const handleDrawerClose = (done: () => void) => {
    done()
}

// 高级搜索查询
const searchWithAdvanced = () => {
    // 将高级搜索条件映射到基础搜索参数
    info.customercode = advancedSearch.customerCode
    info.customerState = advancedSearch.customerState
    info.industryId = advancedSearch.industryId
    info.userid = advancedSearch.userId

    // 重置分页
    page.pageindex = 1

    // 调用查询接口，传递所有高级搜索参数
    myaxios.get('/api/Customer/GetCustomer', {
        params: {
            customerCode: advancedSearch.customerCode,
            customerName: advancedSearch.customerName,
            industryId: advancedSearch.industryId,
            customerSourceId: advancedSearch.customerSourceId,
            customerContact: advancedSearch.customerContact,
            contactPhone: advancedSearch.contactPhone,
            customerEmail: advancedSearch.customerEmail,
            organizationId: advancedSearch.organizationId,
            userId: advancedSearch.userId,
            customerState: advancedSearch.customerState,
            contactAddress: advancedSearch.contactAddress,
            financeName: advancedSearch.financeName,
            taxpayerNumber: advancedSearch.taxpayerNumber,
            bankAccount: advancedSearch.bankAccount,
            accountBank: advancedSearch.accountBank,
            createor: advancedSearch.createor,
            startTime: advancedSearch.createTimeRange[0] || '',
            endTime: advancedSearch.createTimeRange[1] || '',
            pageindex: page.pageindex,
            pagesize: page.pagesize
        }
    }).then(res => {
        tableData.value = res.data.data.data;
        page.listCount = res.data.data.listCount;
        page.pageCount = res.data.data.pageCount;
        drawerVisible.value = false
        ElMessage.success('查询成功')
    }).catch(err => {
        console.error('高级搜索失败:', err)
        ElMessage.error('查询失败')
    })
}

</script>

<style scoped>
.pager-bar {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 16px;
    flex-wrap: wrap;
}

.pager-group {
    display: flex;
    align-items: center;
    gap: 8px;
}

.pager-info {
    color: #666;
    white-space: nowrap;
    font-size: 12px;
}

/* 高级搜索抽屉样式 */
.advanced-search-drawer {
    --el-drawer-bg-color: #f8fafc;
}

.advanced-search-drawer .el-drawer__header {
    margin-bottom: 0;
    padding: 20px 24px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-bottom: none;
}

.drawer-header {
    display: flex;
    align-items: center;
    color: white;
}

.header-icon {
    font-size: 20px;
    margin-right: 12px;
}

.header-title {
    font-size: 18px;
    font-weight: 600;
}

.drawer-content {
    padding: 24px;
    height: calc(100vh - 140px);
    overflow-y: auto;
}

.advanced-search-form {
    background: transparent;
}

.search-section {
    background: white;
    border-radius: 12px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    border: 1px solid #e4e7ed;
    transition: all 0.3s ease;
}

.search-section:hover {
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.12);
    transform: translateY(-2px);
}

.section-header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 12px;
    border-bottom: 2px solid #f0f2f5;
}

.section-icon {
    font-size: 18px;
    margin-right: 10px;
    color: #409eff;
}

.section-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
}

.advanced-search-form .el-form-item {
    margin-bottom: 18px;
}

.advanced-search-form .el-form-item__label {
    font-weight: 500;
    color: #606266;
}

.select-input {
    cursor: pointer;
}

.select-input .el-input__inner {
    cursor: pointer;
}

.search-icon {
    color: #409eff;
    cursor: pointer;
}

.search-icon:hover {
    color: #66b1ff;
}

.drawer-footer {
    padding: 20px 24px;
    background: white;
    border-top: 1px solid #e4e7ed;
    box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
}

.footer-actions {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}

.footer-actions .el-button {
    min-width: 80px;
}

/* 输入框和选择器样式优化 */
.advanced-search-form .el-input {
    border-radius: 8px;
}

.advanced-search-form .el-select {
    border-radius: 8px;
}

.advanced-search-form .el-date-editor {
    border-radius: 8px;
}

/* 状态选项样式 */
.el-select-dropdown__item span {
    display: flex;
    align-items: center;
}

/* 响应式设计 */
@media (max-width: 1024px) {
    .advanced-search-drawer {
        --el-drawer-size: 35% !important;
    }
}

@media (max-width: 768px) {
    .advanced-search-drawer {
        --el-drawer-size: 50% !important;
    }

    .drawer-content {
        padding: 16px;
    }

    .search-section {
        padding: 16px;
    }
}

/* 表头设置弹窗样式 */
.column-settings {
    max-height: 400px;
    overflow-y: auto;
}

.settings-header {
    display: flex;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #ebeef5;
    font-weight: 600;
    color: #606266;
}

.settings-header span:first-child {
    width: 60px;
    text-align: center;
}

.settings-header span:nth-child(2) {
    flex: 1;
    padding-left: 12px;
}

.settings-header span:last-child {
    width: 100px;
    text-align: center;
}

.column-list {
    margin-top: 12px;
}

.column-item {
    display: flex;
    align-items: center;
    padding: 8px 0;
    border-bottom: 1px solid #f5f7fa;
    transition: background-color 0.3s ease;
}

.column-item:hover {
    background-color: #f8f9fa;
}

.column-item .el-checkbox {
    width: 60px;
    display: flex;
    justify-content: center;
}

.column-name {
    flex: 1;
    padding-left: 12px;
    color: #303133;
}

.column-actions {
    width: 100px;
    display: flex;
    justify-content: center;
    gap: 4px;
}

.column-actions .el-button {
    padding: 4px 8px;
    min-height: auto;
    font-size: 12px;
    border: 1px solid #dcdfe6;
}

.column-actions .el-button:hover {
    color: #409eff;
    border-color: #409eff;
}

.column-actions .el-button:disabled {
    color: #c0c4cc;
    border-color: #e4e7ed;
    cursor: not-allowed;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}

/* 表头设置弹窗动画 */
.el-dialog {
    border-radius: 8px;
}

.el-dialog__header {
    padding: 20px 20px 10px;
    border-bottom: 1px solid #ebeef5;
}

.el-dialog__title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
}

.el-dialog__body {
    padding: 20px;
}

.el-dialog__footer {
    padding: 10px 20px 20px;
    border-top: 1px solid #ebeef5;
}

/* 优化表单项间距 */
.advanced-search-form .el-form-item {
    margin-bottom: 12px;
}

.advanced-search-form .el-form-item__label {
    font-size: 13px;
    padding-right: 8px;
}

/* 优化区域间距 */
.search-section {
    margin-bottom: 16px;
    padding: 16px;
}

.section-header {
    margin-bottom: 12px;
    padding-bottom: 6px;
}

/* 表格优化样式 */
:deep(.el-table) {
    font-size: 13px;
}

:deep(.el-table th) {
    background-color: #f5f7fa;
    color: #606266;
    font-weight: 600;
    padding: 12px 0;
}

:deep(.el-table td) {
    padding: 12px 0;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
    background-color: #fafafa;
}

:deep(.el-table .el-table__row:hover > td) {
    background-color: #f5f7fa !important;
}

/* 数字文本样式 */
.number-text {
    font-family: 'Courier New', monospace;
    letter-spacing: 0.5px;
    color: #303133;
}

/* 链接样式优化 */
:deep(.el-link) {
    font-weight: 500;
}

/* 标签样式优化 */
:deep(.el-tag) {
    border-radius: 4px;
    font-weight: 500;
}

/* 操作按钮样式 */
:deep(.el-table .el-button--link) {
    padding: 4px 8px;
    margin: 0 4px;
    font-weight: 500;
}

:deep(.el-table .el-button--link:hover) {
    text-decoration: underline;
}

/* 表格边框优化 */
:deep(.el-table--border) {
    border: 1px solid #ebeef5;
}

:deep(.el-table--border th),
:deep(.el-table--border td) {
    border-right: 1px solid #ebeef5;
}

/* 固定列阴影 */
:deep(.el-table__fixed),
:deep(.el-table__fixed-right) {
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.12);
}

/* 表格卡片样式 */
.el-card {
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

/* 优化表格滚动条 */
:deep(.el-table__body-wrapper) {
    scrollbar-width: thin;
    scrollbar-color: #c1c1c1 #f1f1f1;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar) {
    width: 8px;
    height: 8px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-track) {
    background: #f1f1f1;
    border-radius: 4px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
    background: #c1c1c1;
    border-radius: 4px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb:hover) {
    background: #a8a8a8;
}
</style>
